package com.weifangfirecontrolformal.weifangfirecontrolformal.web.service.other;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.weifangfirecontrolformal.weifangfirecontrolformal.common.base.BaseService;
import com.weifangfirecontrolformal.weifangfirecontrolformal.common.utils.appkit.ConfigKit;
import com.weifangfirecontrolformal.weifangfirecontrolformal.support.model.RespEntity;
import com.weifangfirecontrolformal.weifangfirecontrolformal.web.service.noticeannouncement.NoticeannouncementService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class UploadsService extends BaseService {
    private static final Logger logger = LoggerFactory.getLogger(NoticeannouncementService.class);
    protected String[] FILE_UPLOAD_IMG_EXTS = { "jpg", "png", "gif", "jpeg", "bmp", "zip","xlsx","txt","docx","doc","xls","jar", "mp4", "mp3", "pdf", "blob"};
    public RespEntity addPicture(JSONObject jsonObject) {
        return this.restJava(jsonObject, "businessJava", "add", "picture");
    }

    /**
     * @Author YangYu
     * @Description 上传文件
     * @Date Created in 15:34 2024/6/5
     * @Param [params, request]
     */

    public RespEntity uploadFile(@RequestParam Map<String, Object> params, HttpServletRequest request){

        JSONObject jsonObject = new JSONObject();
        jsonObject.putOpt("token",params.get("token"));
        RespEntity respEntity = restJava(jsonObject, "systemsetupJava", "getDecodeTokenNew", "systemsetup");
        if (respEntity.getCode() == 401){
            return RespEntity.expire();
        }
        List<String> fileNameLsit = new ArrayList<String>();
        Map<String,Object> allMap = new HashMap<>();
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (!commonsMultipartResolver.isMultipart(request)) {
            return RespEntity.fail("无法从Request中获取文件对象");
        }
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
        Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
        String paths = "";
        while (fileNames.hasNext()) {
            String fileName = fileNames.next();
            MultipartFile multipartFile = multipartHttpServletRequest.getFile(fileName);
            if (multipartFile == null) {
                return RespEntity.fail(StrUtil.format("未成功获取文件对象", fileName));
            } else if (multipartFile.isEmpty()) {
                return RespEntity.fail(StrUtil.format("成功获取文件对象,但无法获取名为{}的文件", fileName));
            }
            String repath = ConfigKit.getStr("physicalPath", "upload")+"/"+ DateUtil.now().split(" ")[0].replace("-","");
            StringBuffer url = request.getRequestURL();
            //String webPath = url.toString().replace("/uploads", "/download?fileName=");
            String webPath = ConfigKit.getStr("networkPath", "upload") + DateUtil.now().split(" ")[0].replace("-","")+"/";
            // 原始文件名
            String oldFileName = multipartFile.getOriginalFilename();
            String[] arrTmp = oldFileName.split("\\.");
            String ext = arrTmp[arrTmp.length - 1];
            int count = 0;
            for (String _ext : FILE_UPLOAD_IMG_EXTS) {
                if (_ext.equalsIgnoreCase(ext)) {
                    count++;
                }
            }
            if (count < 1) {
                return RespEntity.fail(StrUtil.format("文件后缀{}不合法", ext));
            }
            String newFileName = "";
            if (ext.equals("blob")){
                newFileName = System.currentTimeMillis() + ".jpg";
            }else {
                newFileName = System.currentTimeMillis() + "." + ext;
            }

            File file = new File(repath);
            if (!file.exists()) {
                file.mkdirs();
            }
            file = new File(repath + "/" + newFileName);
            try {
                multipartFile.transferTo(file);
                //fileNameLsit.add(webPath + newFileName);
                allMap.put("filePath",webPath + newFileName);
                allMap.put("fileName",multipartFile.getOriginalFilename());
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
                return RespEntity.fail(StrUtil.format("图片保存失败:{}", e.getMessage()));
            }
        }
        return RespEntity.success(allMap);
    }
}
